<?php 

declare(strict_types=1);

namespace WanZ\App\Utils;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Context\Context;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

/**
 * Class JwtBuilder
 * @package WanZ\App\Utils
 */
class JwtBuilder
{
	/**
	 * 生成普通用户的JWT
	 * @param int $companyId
	 * @param int $userId
	 * @param int $userType
	 * @return array
	 * @throws CommonException
	 */
	public function genUserToken(int $companyId, int $userId, int $userType, int $isSuper = 1, int $isAdmin = 0): array
	{
		if ($companyId <= 0 || $userId <= 0 || $userType <= 0) throw new CommonException(ErrorCode::INVALID_PARAMS, '生成JWT的参数非法');
		// 签名对象
		$signer = new Sha256();
		$key = new Key(config('jwt.user.secret', ''));

        $miniSource = Context::get('minSource', 'wz');

		// 获取当前时间戳
		$time = time();
		$exp = $time + config('jwt.user.expire', 86400);
		// 设置签发人、接收人、唯一标识、签发时间、立即生效、过期时间、用户id、签名
		$token = (new Builder())
			// ->issuedBy(self::$_config['iss'])
			->withHeader('alg', config('jwt.user.alg', 'HS265'))
			->issuedAt($time)
			->canOnlyBeUsedAfter($time - 1)
			->expiresAt($exp)
			->withClaim('u_id', $userId)
			->withClaim('u_type', $userType)
			->withClaim('company_id', $companyId)
			->withClaim('iss', config('jwt.user.iss', ''))
            ->withClaim('is_super', $isSuper)
            ->withClaim('is_admin', $isAdmin)
            ->withClaim('mini_source', $miniSource)
			->getToken($signer, $key);

		return ['token' => (string)$token, 'expire_at' => $exp];
	}
}
